package com.wwg.spring.bean.factory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MyBeanFactory {

    private static MyBeanFactory myBeanFactory;

    static {
         myBeanFactory = new MyBeanFactory();
    }

    private MyBeanFactory() {
    }

    private List<BeanDefined> beanDefinedList;
    private Map<String, String> beanDefinedMap;

    public static MyBeanFactory getMyBeanFactory() {
        return myBeanFactory;
    }

    public Map<String, String> getBeanDefinedMap() {
        return beanDefinedMap;
    }

    public void setBeanDefinedMap(Map<String, String> beanDefinedMap) {
        this.beanDefinedMap = beanDefinedMap;
    }

    public Object getBean(BeanDefined beanDefined) {
        String definedId = beanDefined.getDefinedId();
        String classPath = beanDefined.getClassPath();

        Object o = null;
        // 反射获取注册进去的bean
        if (classPath != null && classPath.equals(this.beanDefinedMap.get(definedId))) {
            try {
                Class<?> aClass = Class.forName(classPath);
                o = aClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return o;
    }

    public  void setBenDefinedList(List<BeanDefined> beanDefinedList) {
        this.beanDefinedList = beanDefinedList;
        this.beanDefinedMap = beanDefinedList.stream().collect(Collectors.toMap(BeanDefined::getDefinedId,BeanDefined::getClassPath,(n1,n2)->n2));


    }

    public List<BeanDefined> getBeanDefinedList() {
        return beanDefinedList;
    }

    public void setBeanDefinedList(List<BeanDefined> beanDefinedList) {
        this.beanDefinedList = beanDefinedList;
    }
}
